package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.*;
import com.baomidou.ant.mapper.WorkOrderMapper;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.MyDateUtil;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.utils.TemplateExcelUtils;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements IWorkOrderService {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IProcessInfoService processInfoService;
    @Autowired
    private IParentOrderService parentOrderService;
    @Autowired
    private IReportOrderService reportOrderService;
    @Autowired
    private IAllMachineService allMachineService;
    @Autowired
    private IProcessConditionService processConditionService;
    @Autowired
    private IPinLibraryService pinLibraryService;
    @Autowired
    private IMachineInfoService machineInfoService;
    @Autowired
    private ICoreLibraryService coreLibraryService;
    @Value("${file.templateFileName}")
    private String templateFileName;
    @Value("${file.destFileName}")
    private String destFileName;
    @Value("${file.retentionPath}")
    private String retentionPath;

    @Override
    public IPage<ResponseOrderListVo> orderList(RequestListOrderVo requestListOrderVo) {
        IPage<WorkOrder> orderIPage=new Page<>(requestListOrderVo.getDisplayStart(),requestListOrderVo.getDisplayLength());
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        //工单号查询
        if(StringUtils.isNotBlank(requestListOrderVo.getOrderNum())){
            queryWrapper.like("order_num",requestListOrderVo.getOrderNum());
        }
        //创建人查询
        if(StringUtils.isNotBlank(requestListOrderVo.getCreateBy())){
            queryWrapper.like("create_by",requestListOrderVo.getCreateBy());
        }
        //产品类型查询
        if(ObjectUtils.isNotEmpty(requestListOrderVo.getPinId())){
            queryWrapper.eq("pin_id",requestListOrderVo.getPinId());
        }
        //状态查询
        if(StringUtils.isNotBlank(requestListOrderVo.getStatus())){
            if(Objects.equals(requestListOrderVo.getStatus(), "3")){
                queryWrapper.eq("is_check",false);
            }else{
                queryWrapper.eq("order_status",requestListOrderVo.getStatus());
                queryWrapper.eq("is_check",true);
            }
        }
        //待办筛选
        if(StringUtils.isNotBlank(requestListOrderVo.getWorkerNo())){
            queryWrapper.like("worker_no",requestListOrderVo.getWorkerNo());
        }
        //时间排序
        if(ObjectUtils.isEmpty(requestListOrderVo.getSortStatus())){
            queryWrapper.orderByAsc("create_time");
            queryWrapper.orderByAsc("order_num");
        }else{
            if (Objects.equals(requestListOrderVo.getSortStatus(), "desc")) {
                queryWrapper.orderByDesc("create_time");
            }
            if (Objects.equals(requestListOrderVo.getSortStatus(), "asc")) {
                queryWrapper.orderByAsc("create_time");
            }
            //工单号排序
            if (Objects.equals(requestListOrderVo.getSortStatus(), "lotDesc")) {
                queryWrapper.orderByDesc("order_num");
            }
            if (Objects.equals(requestListOrderVo.getSortStatus(), "lotAsc")) {
                queryWrapper.orderByAsc("order_num");
            }
        }
        SysUser user=userService.getById(requestListOrderVo.getUserId());
        //判断管理员级别
        if(Objects.equals(user.getType(), "1")){
            //管理员条件查询
            if(ObjectUtils.isNotEmpty(requestListOrderVo.getOrderDept())){
                queryWrapper.eq("order_dept",requestListOrderVo.getOrderDept());
            }
        } else if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//只能看自己部门的
            queryWrapper.eq("order_dept",user.getDeptId());
        }
        Integer allTotal=list(queryWrapper).size();
        //得到结果集
        IPage<WorkOrder> orderPage=page(orderIPage,queryWrapper);
        //返回处理结果
        return orderPage.convert(order -> {
            ResponseOrderListVo vo=new ResponseOrderListVo();
            BeanUtils.copyProperties(order,vo);
            //父工单查询
            ParentOrder parentOrder=parentOrderService.getById(order.getParentId());
            vo.setLotNo(parentOrder.getLotNo());
            vo.setAllTotal(allTotal);
            vo.setPinName(pinLibraryService.getById(parentOrder.getPinId()).getPinName());
            if(order.getNowProcess()!=0){
                ProcessInfo processInfo=processInfoService.getById(order.getNowProcess());
                vo.setNowProcess(processInfo.getProcessName());
            }
            return vo;
        });
    }

    @Override
    public WorkOrder queryByOrderNum(String orderNum) {
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",orderNum);
        return getOne(queryWrapper);
    }


    @Override
    public boolean updateOrder(RequestUpdateOrderVo requestUpdateOrderVo) {
        WorkOrder workOrder=getById(requestUpdateOrderVo.getId());
        BeanUtils.copyProperties(requestUpdateOrderVo,workOrder);
        Integer amount= MyStringUtil.returnNumber(requestUpdateOrderVo.getAmountUnit());
        String unit=MyStringUtil.returnUnit(requestUpdateOrderVo.getAmountUnit());
        workOrder.setAmountPlan(amount);
        workOrder.setUnit(unit);
        return updateById(workOrder);
    }

    @Override
    public void addWorkOrder(ParentOrder parentOrder,String[] workerList) {
        //生成子工单数量
        int childrenNum=(int)Math.ceil((double) parentOrder.getTotalAmount() /(double)parentOrder.getAcceptAmount());
        //得到余数
        int mantissa=parentOrder.getTotalAmount()%parentOrder.getAcceptAmount();
        for(int str=1;str<=childrenNum;str++){
            String orderNum=parentOrder.getLotNo()+MyStringUtil.sequenceCode(str,childrenNum);//生成子工单号
            WorkOrder workOrder=new WorkOrder();
            workOrder.setOrderNum(orderNum);
            BeanUtils.copyProperties(parentOrder,workOrder);
            int[] ids=MyStringUtil.toInt(parentOrder.getProcess());
            workOrder.setNowProcess(ids[0]);
            //判断是否有下道工序
            if(ids.length>1){
                workOrder.setNextProcess(ids[1]);
            }else
                workOrder.setNextProcess(0);
            //设置当前工序的执行人信息
            if (workerList[0].contains(",")) {//如果一次指派多个
                String[] nowWorkerNoList=workerList[0].split(",");
                String[] nowWorkerNameList=new String[nowWorkerNoList.length];
                for(int i=0;i<nowWorkerNoList.length;i++){
                    nowWorkerNameList[i]=userService.queryByLoginName(nowWorkerNoList[i]).getUserName();
                }
                String nowWorker= MyStringUtil.strToString(nowWorkerNameList);
                workOrder.setNowWorker(nowWorker);
                workOrder.setWorkerNo(workerList[0]);
            }else{//只指派一个
                if(ObjectUtils.isNotEmpty(workerList[0])) {//用户没选
                    SysUser nowWorker = userService.queryByLoginName(workerList[0]);
                    workOrder.setNowWorker(nowWorker.getUserName());
                    workOrder.setWorkerNo(nowWorker.getLoginName());
                }else{
                    workOrder.setNowWorker("上报人自选");
                    workOrder.setWorkerNo("0");
                }
            }
            workOrder.setAllWorkers(MyStringUtil.strToString(workerList));
            workOrder.setParentId(parentOrder.getId());
            if(mantissa!=0&&str==childrenNum){//余数不为0，则代表最后一单余数
                workOrder.setAmountPlan(mantissa);
            }else
                workOrder.setAmountPlan(parentOrder.getAcceptAmount());
            save(workOrder);
        }
    }

    @Override
    public boolean reWorker(RequestReWorkerVo vo) {
        WorkOrder workOrder=getById(vo.getId());
        int[] processIds=MyStringUtil.toInt(workOrder.getProcess());
        String[] workerList=workOrder.getAllWorkers().split(";");
        String goalWorker=vo.getWorkerNo();
        //判断设置的是哪道工序的人员
        for(int i=0;i<processIds.length;i++){
            if(processIds[i]==vo.getGoalProcess()){
                //更改
                workerList[i]=goalWorker;
            }
        }
        //如果更改的是当前正在进行的工序
        if(Objects.equals(vo.getGoalProcess(), workOrder.getNowProcess())){
            workOrder.setNowWorker(vo.getNowWorker());
            workOrder.setWorkerNo(vo.getWorkerNo());
        }
        //保存新的人员
        workOrder.setAllWorkers(MyStringUtil.strToString(workerList));
        return updateById(workOrder);
    }

    @Override
    public ResponseOrderInfoVo getOrderInfo(WorkOrder workOrder) {
        ResponseOrderInfoVo vo=new ResponseOrderInfoVo();
        BeanUtils.copyProperties(workOrder,vo);
        ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
        vo.setLotNo(parentOrder.getLotNo());
        if(parentOrder.getCoreId()==0){
            vo.setCorePin("上报人自选");
        }else
            vo.setCorePin(coreLibraryService.getById(parentOrder.getPinId()).getCorePin());
        //检录机台信息
        if(!workOrder.isCheck()){
            vo.setCheckMachine("该工单未检录");
        }else{
            if(vo.getCheckMachineId()==null||vo.getCheckMachineId()==0){
                vo.setCheckMachine("上报人自选");
            }else
                vo.setCheckMachine(machineInfoService.getById(vo.getCheckMachineId()).getMachineModel());
        }
        int[] processIds=MyStringUtil.toInt(workOrder.getProcess());
        String[] allWorkers=workOrder.getAllWorkers().split(";");
        //判断是否事先指定工作人员
        if(allWorkers.length==0){//说明一个也没指定
            vo.setNextWorker("上报人自选");
            vo.setPastWorker("上报人自选");
        }else{//指定了
            int index=0;
            //得到上个任务的指派人员
            if(workOrder.getPastProcess()==0){
                vo.setPastWorker("无");
            }else{
                for(int i=0;i<processIds.length;i++){
                    if(processIds[i]==workOrder.getPastProcess()){
                        index=i;
                        break;
                    }
                }
                //如发生指定了但没全指定的情况
                if(ObjectUtils.isEmpty(allWorkers[index])){
                    vo.setPastWorker("上报人自选");
                }else {//多人协作的情况下
                    if (allWorkers[index].contains(",")) {
                        String[] pastWorkerNos = allWorkers[index].split(",");
                        String[] pastWorkerNames = new String[pastWorkerNos.length];
                        for (int i = 0; i < pastWorkerNos.length; i++) {
                            SysUser user = userService.queryByLoginName(pastWorkerNos[i]);
                            pastWorkerNames[i] = user.getUserName();
                        }
                        vo.setPastWorker(MyStringUtil.strToString(pastWorkerNames));
                    } else//非多人协作的情况下
                        vo.setPastWorker(userService.queryByLoginName(allWorkers[index]).getUserName());
                }
            }
            //得到下个任务指派人员
            if(workOrder.getNextProcess()==0){
                vo.setNextWorker("无");
            }else{
                for(int i=0;i<processIds.length;i++){
                    if(processIds[i]==workOrder.getNextProcess()){
                        index=i;
                        break;
                    }
                }if(ObjectUtils.isEmpty(allWorkers[index])){
                    vo.setNextWorker("上报人自选");
                }else {
                    if (allWorkers[index].contains(",")) {
                        String[] nextWorkerNos = allWorkers[index].split(",");
                        String[] nextWorkerNames = new String[nextWorkerNos.length];
                        for (int i = 0; i < nextWorkerNos.length; i++) {
                            SysUser user = userService.queryByLoginName(nextWorkerNos[i]);
                            nextWorkerNames[i] = user.getUserName();
                        }
                        vo.setNextWorker(MyStringUtil.strToString(nextWorkerNames));
                    } else
                        vo.setNextWorker(userService.queryByLoginName(allWorkers[index]).getUserName());
                }
            }
        }
        return vo;
    }

    @Override
    public ResponseWorkerInfoVo getWorkerInfo(WorkOrder workOrder) {//定义返回涉及工序
        ResponseWorkerInfoVo resultVo=new ResponseWorkerInfoVo();
        int[] processIds= MyStringUtil.toInt(workOrder.getProcess());
        String[] process =new String[processIds.length];
        for(int i=0;i<processIds.length;i++){
            process[i]=processInfoService.getById(processIds[i]).getProcessName();
        }
        //定义返回涉及人员
        String[] workerNos=workOrder.getAllWorkers().split(";");
        //如果一个都没事先指派
        if(workerNos.length==0){
            String[] resultWorkers=new String[process.length];
            for(int i=0;i<process.length;i++){
                resultWorkers[i]="未指派人员";
            }
            //结果集写入返回体
            ResponseWorkerInfoVo vo=new ResponseWorkerInfoVo();
            vo.setProcessList(process);
            vo.setWorkerList(resultWorkers);
            BeanUtils.copyProperties(vo,resultVo);
        }else {
            //定义返回结果长度
            String[] resultWorkers=new String[process.length];
            for(int i=0;i<workerNos.length;i++){
                if(ObjectUtils.isEmpty(workerNos[i])){
                    resultWorkers[i]="未指派人员";
                }else {//如果是多人一道工序
                    if (workerNos[i].contains(",")) {
                        //分割工号,得到这些人的信息
                        String[] thisWorker = workerNos[i].split(",");
                        String[] workers = new String[thisWorker.length];
                        for (int j = 0; j < thisWorker.length; j++) {
                            SysUser user = userService.queryByLoginName(thisWorker[j]);
                            workers[j] = user.getUserName();
                        }
                        resultWorkers[i] = MyStringUtil.strToString(workers);//拼接好结果返回
                    } else {
                        //一人的工序
                        SysUser user = userService.queryByLoginName(workerNos[i]);
                        resultWorkers[i] = user.getUserName();
                    }
                }
            }
            //校验resultWorkers
            for(int i=0;i<resultWorkers.length;i++){
                if(resultWorkers[i]==null){
                    resultWorkers[i]="未指派人员";
                }
            }
            //结果集写入返回体
            ResponseWorkerInfoVo vo=new ResponseWorkerInfoVo();
            vo.setProcessList(process);
            vo.setWorkerList(resultWorkers);
            BeanUtils.copyProperties(vo,resultVo);
        }
        return resultVo;
    }

    @Override
    public List<String> getProcessName(Integer id) {
        WorkOrder workOrder=getById(id);
        //得到工序id集
        String result;
        int[] processIds = MyStringUtil.toInt(workOrder.getProcess());
        String[] process = new String[processIds.length];
        for (int i = 0; i < processIds.length; i++) {
            if(processIds[i]==0){continue;}
            ProcessInfo processInfo = processInfoService.getById(processIds[i]);
            process[i] = processInfo.getProcessName();
        }
        result = MyStringUtil.strToString(process);
        //得到完成工序的工序集
        String over;
        if(Objects.equals(workOrder.getOverProcess(), "0")){
            over="无";
        }else {
            int[] overIds = MyStringUtil.toInt(workOrder.getOverProcess());
            String[] overProcess = new String[overIds.length];
            for (int i = 0; i < overIds.length; i++) {
                if(overIds[i]==0){continue;}
                ProcessInfo processInfo = processInfoService.getById(overIds[i]);
                overProcess[i] = processInfo.getProcessName();
            }
            over = MyStringUtil.strToString(overProcess);
        }
        String nowP;
        String pastP;
        String nextP;
        if(workOrder.getNowProcess()==null||workOrder.getNowProcess()==0){
            nowP="无";
        }else
            nowP=processInfoService.getById(workOrder.getNowProcess()).getProcessName();
        if(workOrder.getPastProcess()==null||workOrder.getPastProcess()==0){
            pastP="无";
        }else
            pastP=processInfoService.getById(workOrder.getPastProcess()).getProcessName();
        if(workOrder.getNextProcess()==null||workOrder.getNextProcess()==0){
            nextP="无";
        }else
            nextP=processInfoService.getById(workOrder.getNextProcess()).getProcessName();
        List<String> resultList=new ArrayList<>();
        resultList.add(result);
        resultList.add(over);
        resultList.add(nowP);
        resultList.add(pastP);
        resultList.add(nextP);
        return resultList;
    }

    @Override
    public void exportTemplateProvinceAreaData(HttpServletResponse response, String orderId) {
        try {
            WorkOrder workOrder=getById(Integer.parseInt(orderId));
            //空的工单不做操作
//            if(workOrderList.size()!=0){
//            }
            //得到工单的产品信息,用于找到指定模板
            ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
            String fileName="";
//            PinLibrary pinLibrary=pinLibraryService.getById(parentOrder.getPinId());
            //得到模板路径，在用的
            QueryWrapper<ProcessCondition> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("pin_id",parentOrder.getPinId());
            queryWrapper.eq("mould_status",1);
            ProcessCondition processCondition=processConditionService.list(queryWrapper).get(0);
            //数据填入
            Map<String,Object> param = new HashMap<>();
            param.put("orderNum",workOrder.getOrderNum());
            param.put("acceptAmount",workOrder.getAmountPlan());
            fileName=MyStringUtil.strToStringOfFileName(fileName,workOrder.getOrderNum());

            //文件路径
            //pinLibrary.getPinName()+".xlsx"
            TemplateExcelUtils.downLoadExcel(fileName,processCondition.getMouldPath(),param,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int totalSize(RequestDtoVo requestDtoVo) {
        SysUser sysUser=userService.getById(requestDtoVo.getUserId());
        List<WorkOrder> workOrderList=new ArrayList<>();
        //管理员判断
        if(Objects.equals(sysUser.getType(), "0")){//是二级管理员
            QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("order_dept",sysUser.getDeptId());
            workOrderList=list(queryWrapper);
        } else if(Objects.equals(sysUser.getType(), "1")){//是超级管理员
            workOrderList=list();
        }else if(Objects.equals(sysUser.getType(), "2")){//普通作业员
            QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("order_dept",sysUser.getDeptId());
            queryWrapper.eq("worker_no",sysUser.getLoginName());
            workOrderList=list(queryWrapper);
        }
        return workOrderList.size();
    }

    @Override
    public List<ResponsePutProcessVo> putProcess(WorkOrder workOrder) {
        int[] processIds=MyStringUtil.toInt(workOrder.getProcess());
        List<Integer> processList = Arrays.stream(processIds).boxed().collect(Collectors.toList());
        int[] overProcessIds=MyStringUtil.toInt(workOrder.getOverProcess());
        List<Integer> overProcessList = Arrays.stream(overProcessIds).boxed().collect(Collectors.toList());
        List<Integer> resultList = processList.stream().filter(item -> !overProcessList.contains(item)).collect(Collectors.toList());
        List<ResponsePutProcessVo> voList=new ArrayList<>();
        for(int i:resultList){
            ProcessInfo processInfo=processInfoService.getById(i);
            ResponsePutProcessVo vo=new ResponsePutProcessVo();
            vo.setProcessId(i);
            vo.setProcessName(processInfo.getProcessName());
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public boolean checkWorker(String[] workerList){
        //定义:委派人员工号集
        List<String> workerNameList=new ArrayList<>();
        //遍历指定的人员
        for(String workerNo:workerList){
            //如果指派人了多人
            if(workerNo.contains(",")){
                String[] thisWorker=workerNo.split(",");
                //依次存入委派人员工号集
                Collections.addAll(workerNameList, thisWorker);
            }else
                workerNameList.add(workerNo);
        }
        //判断重复
        HashSet<String> set=new HashSet();
        for(String i:workerNameList){
            set.add(i);
        }
        return set.size() == workerNameList.size();
    }

    @Override
    public ResponseProductionFlowVo getFlow(String orderNum) {
        WorkOrder workOrder=queryByOrderNum(orderNum);
        ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
        ResponseProductionFlowVo vo=new ResponseProductionFlowVo();
        //值赋予
        vo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(workOrder.getCreateTime()));
        vo.setOrderNum(workOrder.getOrderNum());
        //品名
        PinLibrary pinLibrary=pinLibraryService.getById(parentOrder.getPinId());
        vo.setPinName(pinLibrary.getPinName());
        //每道工序涉及数据
        int[] processIds=MyStringUtil.toInt(workOrder.getProcess());
        Integer[] amountsPlans=new Integer[processIds.length];
        String[] processNames =new String[processIds.length];
        String[] machineMessages =new String[processIds.length];
        Integer[] amounts =new Integer[processIds.length];
        Integer[] badAmounts =new Integer[processIds.length];
        String[] workers =new String[processIds.length];
        String[] reporters =new String[processIds.length];
        String[] reportTimes =new String[processIds.length];
        //所有机台信息，按工序顺序
        for(int i=0;i<processIds.length;i++){
            processNames[i]=processInfoService.getById(processIds[i]).getProcessName();
            QueryWrapper<ReportOrder> reportOrderQueryWrapper=new QueryWrapper<>();
            reportOrderQueryWrapper.eq("order_num",workOrder.getOrderNum());
            reportOrderQueryWrapper.eq("report_process",processIds[i]);
            //得到工序的上报记录
            List<ReportOrder> reportOrderList=reportOrderService.list(reportOrderQueryWrapper);
            if(reportOrderList==null||reportOrderList.size()==0){//没有上报记录
                machineMessages[i]="暂无报工信息";
                amounts[i]=0;
                badAmounts[i]=0;
                workers[i]="暂无报工信息";
                reporters[i]="暂无报工信息";
                reportTimes[i]="暂无报工信息";
            }else{
                //初始化值
                String machineMessage="";
                int amount=0;
                int badAmount=0;
                String worker="";
                String reporter="";
                String reportTime;
                //得到值
                for(ReportOrder reportOrder:reportOrderList){
                    machineMessage=MyStringUtil.strToString(reportOrder.getMachineNum(),machineMessage);
                    amount+=reportOrder.getReportAmount();
                    badAmount+=reportOrder.getBadAmount();
                    //得到工作人员
                    worker=MyStringUtil.strToString(reportOrder.getProcessWorker(),worker);
                    //得到上报人
                    reporter=MyStringUtil.strToString(reportOrder.getReporter(),reporter);
                }
                ReportOrder lastOne=reportOrderList.get(reportOrderList.size()-1);
                //最终结算时间
                reportTime=DateTimeFormatter.ofPattern("MM-dd").format(lastOne.getCreateTime());
                //赋予值
                machineMessages[i]=machineMessage;
                amounts[i]=amount;
                badAmounts[i]=badAmount;
                workers[i]=worker;
                reporters[i]=reporter;
                reportTimes[i]=reportTime;
            }
        }
        //计划接收数量
        for(int i=0;i<amounts.length;i++){
            if(i==0){
                amountsPlans[i]=workOrder.getAmountPlan();
            }else
                amountsPlans[i]=amounts[i-1];
        }
        //所需工序
        vo.setAmountPlans(amountsPlans);
        vo.setProcessNames(processNames);
        vo.setMachineMessages(machineMessages);
        vo.setAmounts(amounts);
        vo.setBadAmounts(badAmounts);
        vo.setWorkers(workers);
        vo.setReporters(reporters);
        vo.setReportTimes(reportTimes);
        return vo;
    }

    @Override
    public IPage<ResponseRetentionOrderVo> retentionOrder(RequestRetentionOrderVo vo) {
        IPage<WorkOrder> iPage=new Page<>(vo.getDisplayStart(),vo.getDisplayLength());
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(vo.getOrderNum())){
            queryWrapper.like("order_num",vo.getOrderNum());
        }
        if(ObjectUtils.isNotEmpty(vo.getProcess())){
            queryWrapper.eq("now_process",vo.getProcess());
        }
        //对滞留时间进行排序
        if(Objects.equals(vo.getSortStatus(), "asc")||ObjectUtils.isEmpty(vo.getSortStatus())){
            queryWrapper.orderByDesc("create_now");
        }
        if(Objects.equals(vo.getSortStatus(), "decs")){
            queryWrapper.orderByAsc("create_now");
        }
        SysUser user=userService.getById(vo.getUserId());
        //判断管理员级别
        if(Objects.equals(user.getType(), "1")){
            //管理员条件查询
            if(ObjectUtils.isNotEmpty(vo.getOrderDept())){
                queryWrapper.eq("order_dept",vo.getOrderDept());
            }
        } else if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//二级管理员及以下,只能看自己部门的
            queryWrapper.eq("order_dept",user.getDeptId());
        }
        //找到时间,且必须是已经检录的
        queryWrapper.eq("is_check",true);
        queryWrapper.eq("order_status","0");
        //检录版本更新前不计滞留
        String banTime= MyDateUtil.dateCheckOfDay("2022-07-03");
        if(Objects.equals(vo.getRetentionLevel(), "A")){
            queryWrapper.apply("CONVERT(varchar(30),create_now,120 )  <= CONVERT(varchar(30),getdate() - 1,120)")
                    .apply("CONVERT(varchar(30),create_now,102 )  >= CONVERT(varchar(30),getdate() -"+banTime+",102)");
        }
        if(Objects.equals(vo.getRetentionLevel(), "B")){
            queryWrapper.apply("CONVERT(varchar(30),create_now,120 )  <= CONVERT(varchar(30),getdate() - 3,120)")
                    .apply("CONVERT(varchar(30),create_now,102 )  >= CONVERT(varchar(30),getdate() -"+banTime+",102)");
        }

        IPage<WorkOrder> page=page(iPage,queryWrapper);
        return page.convert(workOrder -> {
            String retentionTime=MyDateUtil.dateCheck(workOrder.getCreateNow());
            ResponseRetentionOrderVo responseRetentionOrderVo = new ResponseRetentionOrderVo();
            BeanUtils.copyProperties(workOrder, responseRetentionOrderVo);
            ParentOrder parentOrder = parentOrderService.getById(workOrder.getParentId());
            responseRetentionOrderVo.setLotNo(parentOrder.getLotNo());
            responseRetentionOrderVo.setPinName(pinLibraryService.getById(parentOrder.getPinId()).getPinName());
            ProcessInfo processInfo=processInfoService.getById(workOrder.getNowProcess());
            responseRetentionOrderVo.setNowProcess(processInfo.getProcessName());
            responseRetentionOrderVo.setRetentionTime(retentionTime + "小时");
            return responseRetentionOrderVo;
        });
    }

    @Override
    public IPage<ResponseInProductionVo> inProduction(RequestInProductionVo vo) {
        IPage<WorkOrder> iPage=new Page<>(vo.getDisplayStart(),vo.getDisplayLength());
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(vo.getProcessId())){
            queryWrapper.eq("now_process",vo.getProcessId());
        }
        SysUser user=userService.getById(vo.getUserId());
        //判断管理员级别
        if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//二级管理员及以下,只能看自己部门的
            queryWrapper.eq("order_dept",user.getDeptId());
        }
        queryWrapper.eq("is_check",true);
        //品名
        if(ObjectUtils.isNotEmpty(vo.getPinId())){
            queryWrapper.eq("pin_id",vo.getPinId());
        }
        //计算数量
        int total=list(queryWrapper).size();
        IPage<WorkOrder> page=page(iPage,queryWrapper);
        //分页返回
        return page.convert(workOrder -> {
            ResponseInProductionVo responseInProductionVo=new ResponseInProductionVo();
            BeanUtils.copyProperties(workOrder,responseInProductionVo);
            ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
            responseInProductionVo.setLotNo(parentOrder.getLotNo());
            responseInProductionVo.setPinName(pinLibraryService.getById(parentOrder.getPinId()).getPinName());
            responseInProductionVo.setTotalAmount(total);
            if(Objects.equals(workOrder.getOverProcess(), "0")){//是第一道工序
                responseInProductionVo.setAcceptAmount(workOrder.getAmountPlan());
            }else
                responseInProductionVo.setAcceptAmount(workOrder.getAmount());
            return responseInProductionVo;
        });
    }

    @Override
    public void changeProcess(Integer orderId, Integer processId) {

    }

    @Override
    public void exportRetentionInfo(HttpServletResponse response, String[] data) {
        try {
            String deptName="全事业部";
            String time="24h以上";
            String processName="全工序站";
            //得到数据
            QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
            if(StringUtils.isNotBlank(data[1])){
                queryWrapper.like("order_num",data[1]);
            }
            //是否缺数
//            if(ObjectUtils.isNotEmpty(vo.getMissingStatus())){
//                queryWrapper.eq("is_missing",vo.getMissingStatus());
//            }
            //工序查询
            if(ObjectUtils.isNotEmpty(data[2])){
                queryWrapper.eq("now_process",data[2]);
                processName=processInfoService.getById(data[2]).getProcessName();
            }
            //是否完工
//            if(ObjectUtils.isNotEmpty(vo.getReportStatus())){
//                queryWrapper.eq("is_over",vo.getReportStatus());
//            }
            SysUser user=userService.queryByLoginName(data[0]);
            //判断管理员级别
            if(Objects.equals(user.getType(), "1")){
                //管理员条件查询
                if(ObjectUtils.isNotEmpty(data[3])){
                    queryWrapper.eq("order_dept",data[3]);
                    deptName=deptService.getById(data[3]).getDept();
                }
            } else if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//二级管理员及以下,只能看自己部门的
                queryWrapper.eq("order_dept",user.getDeptId());
                deptName=deptService.getById(user.getDeptId()).getDept();
            }
            //找到时间,且必须是已经检录的
            queryWrapper.eq("is_check",true);
            queryWrapper.eq("order_status","0");
            if(Objects.equals(data[4], "A")){
                queryWrapper.apply("CONVERT(varchar(30),create_now,120 )  <= CONVERT(varchar(30),getdate() - 1,120)");
            }
            if(Objects.equals(data[4], "B")){
                queryWrapper.apply("CONVERT(varchar(30),create_now,120 )  <= CONVERT(varchar(30),getdate() - 3,120)");
                time="72h以上";
            }
            List<WorkOrder> workOrderList=list(queryWrapper);
            List<ResponseRetentionInfoVo> resultList=new ArrayList<>();
            for(WorkOrder workOrder:workOrderList){
                ResponseRetentionInfoVo vo=new ResponseRetentionInfoVo();
                BeanUtils.copyProperties(workOrder,vo);
                vo.setParentNum(parentOrderService.getById(workOrder.getParentId()).getLotNo());
                vo.setPinName(pinLibraryService.getById(workOrder.getPinId()).getPinName());
                vo.setCreateNow(workOrder.getCreateNow().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                vo.setNowProcess(processInfoService.getById(workOrder.getNowProcess()).getProcessName());
                String retentionTime=MyDateUtil.dateCheck(workOrder.getCreateNow());
                vo.setRetentionTime(retentionTime+"小时");
                resultList.add(vo);
            }
            String fileName="滞留信息报表"+"("+deptName+","+processName+","+time+")";
            //数据填入
            Map<String,Object> param = new HashMap<>();
            param.put("list",resultList);
            TemplateExcelUtils.downLoadExcel(fileName, retentionPath,param,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
